package server

import (
	"fmt"
	"log"
	"net/http"
	"sub-app-server/config"
	"sub-app-server/libs"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:   1024,
	WriteBufferSize:  1024,
	CheckOrigin:      func(r *http.Request) bool { return true },
	HandshakeTimeout: time.Duration(time.Second * 5),
}

var ConnChan = make(chan *Channel)

/*
客户端连接到服务端
*/
func wsHandler(c *gin.Context) {

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)

	if err != nil {
		log.Println("cant upgrade connection:", err)
		return
	}

	ConnChan <- NewChannel(conn)

}

type ReplyData struct {
	Id   int    `json:"id"`
	Info string `json:"info"`
}

type UnlockReply struct {
	Code int       `json:"code"`
	Msg  string    `json:"msg"`
	Data ReplyData `json:"data"`
}

func unlockRequest(ctx *gin.Context) {
	var (
		err error
		id  int
	)

	reply := new(UnlockReply)

	if err = ctx.Bind(reply); err != nil {
		err = libs.NewReportError(err)
		libs.Error(ctx, fmt.Sprintf("%v", err))
		return
	}

	id = reply.Data.Id

	config.Lock.Mux.Lock()

	config.Lock.LockMap[id].Status = reply.Code

	config.Lock.LockMap[id].ResponseInfo = reply.Data.Info

	config.Lock.Mux.Unlock()

	close(config.Lock.LockMap[id].C)
}

func testRequest(ctx *gin.Context) {
	libs.Success(ctx, "ok")
}

func WebServer(port string) {

	gin.SetMode(gin.ReleaseMode)

	r := gin.Default()

	r.LoadHTMLGlob("templates/*")

	r.GET("/ws", wsHandler)

	r.GET("/", func(c *gin.Context) {

		c.HTML(200, "index.html", nil)
	})

	r.POST("/unlock_request", unlockRequest)

	r.GET("/test", testRequest)

	log.Println("WebServer running", port)

	if err := r.Run(port); err != nil {
		log.Println(err)
	}

}
